"""
@Project ：minium-test 
@File    ：base.py
@IDE     ：PyCharm 
@Author  ：kevin
@Date    ：2022/1/25 下午3:45 
"""
import minium
from typing import Optional, Any, Union
from minium import Page
import loguru
import json
import os
from main import PROJECT_PATH


class BasePage:
    _page: Union[Page, Any]
    logger = loguru.logger

    def __init__(self, route="", conf=None):
        super().__init__()
        if not conf:
            with open(os.path.join(PROJECT_PATH, "config.json"), "r") as f:
                conf = json.load(f)
        self.logger.info("启动minium实例...")
        self.logger.info(f"配置信息:\n{conf}")
        self.mini = minium.Minium(conf=conf)
        self.routes = self.mini.app.get_all_pages_path()
        self._page = None
        self.logger.info(f"所有页面路径：\n {self.routes}")

        if route:
            try:
                self._page = self.mini.app.navigate_to(route)
                self.logger.info(f"跳转页面成功，页面路由: {route}, 页面类型：normal")
            except:
                self.logger.warning("跳转到普通页面失败！尝试跳转到tabbar页面！")
                try:
                    self._page = self.mini.app.switch_tab(route)
                    self.logger.info(f"跳转页面成功，页面路由: {route}, 页面类型：tabbar")
                except:
                    raise Exception("跳转到页面失败!")

    def click_element(self, el_info):
        """
        定位并点击一个元素
        :param el_info:
        :return:
        """
        el = self._page.get_element(el_info)
        el.tap()
        self.logger.info(f"定位并成功点击了元素({el_info})")

    def type_element(self, el_info, text):
        """
        定位并对input进行输入
        :param text:
        :param el_info:
        :return:
        """
        el = self._page.get_element(el_info)
        el.input(text)
        self.logger.info(f"定位到了元素：{el}，成功输入了：{text}")


if __name__ == '__main__':
    import minium

    import os



    # conf = {
    #     "project_path": "/Users/zhangyingkai/PycharmProjects/minitest-demo/miniprogram-demo",  # 小程序项目目录地址
    #     "dev_tool_path": "/Applications/wechatwebdevtools.app/Contents/MacOS/cli"  # 开发者工具cli地址，如果没有修改过默认安装路径可不填此项
    # }
    # base = BasePage(conf=conf, route="/pages/login/selflogin")
    # base.click_element("/page/view/view[3]/button")
